package im.starchat.chat.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import im.starchat.chat.R;
import im.starchat.chat.activity.PlayBackActivity;
import im.starchat.chat.activity.StarActivity;
import im.starchat.chat.rest.model.RoomBean;
import im.starchat.chat.utils.Constants;
import im.starchat.chat.utils.PreferencesStorageUtil;
import im.starchat.chat.view.CircularImageButton;
import im.starchat.chat.view.FixedAspectRatioFrameLayout;

/**
 * Created by liuchao on 2/10/16.
 * 直播feed流适配器
 */
public class LiveAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    Context mContext;
    private static final int TYPE_FEED = 1001;
    private static final int TYPE_EMPTY = 1002;
    private List<RoomBean> mList;

    public LiveAdapter(Context context, LiveAdapterCallback liveAdapterCallback) {
        this.mContext = context;
        this.mLiveAdapterCallback = liveAdapterCallback;
    }

    public void refreshData(List<RoomBean> list) {
        this.mList = list;
        notifyDataSetChanged();
    }


    public void addAll(List<RoomBean> list) {
        if (mList != null && list.size() > 0) {
            this.mList.addAll(list);
            notifyDataSetChanged();
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case TYPE_EMPTY:
                return new EmptyHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.view_empty, parent, false));
            case TYPE_FEED:
            default:
                return new FeedHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.live_item, parent, false));

        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        switch (getItemViewType(position)) {
            case TYPE_EMPTY:
                EmptyHolder emptyHolder = (EmptyHolder) holder;
                emptyHolder.mInfoText.setText("暂无新直播");
                break;
            case TYPE_FEED:
                final FeedHolder feedHolder = (FeedHolder) holder;
                feedHolder.imageButtonUserLogo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(v.getContext(), mList.get(position).getUser().getNickname(), Toast.LENGTH_SHORT).show();
                    }
                });
                if (!TextUtils.isEmpty(mList.get(position).getUser().getAvatar())) {
                    Picasso.with(mContext).load(mList.get(position).getUser().getAvatar())
                            .placeholder(R.drawable.home_head)
                            .into(feedHolder.imageButtonUserLogo);
                }
                feedHolder.imageButtonUserLogo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!PreferencesStorageUtil.getUserId(mContext).equals(mList.get(position).getUser().getId())) {
                            Intent viewUserInfointent = new Intent();
                            viewUserInfointent.setClass(mContext, StarActivity.class);
                            viewUserInfointent.putExtra(StarActivity.USER_ID, mList.get(position).getUser().getId());
                            mContext.startActivity(viewUserInfointent);
                        }
                    }
                });
                feedHolder.textViewUserName.setText(mList.get(position).getUser().getNickname());
                //textViewLiveTitle.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                if (!TextUtils.isEmpty(mList.get(position).getDescription())) {
                    feedHolder.textViewContent.setVisibility(View.VISIBLE);
                    feedHolder.textViewContent.setText(mList.get(position).getDescription());
                } else {
                    feedHolder.textViewContent.setVisibility(View.INVISIBLE);
                }
                feedHolder.textViewLiveTitle.setText(mList.get(position).getUser().getDescription());
                feedHolder.textViewLivePraise.setText("" + mList.get(position).getPraises_count() + "赞");
                feedHolder.shareButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mLiveAdapterCallback != null) {
                            mLiveAdapterCallback.onShareBtnClick(mList.get(position));
                        }
                    }
                });
//                String param = mList.get(position).getCoverpath();
//                String root = "http://203.195.167.34/upload/";
//                String url = root + param;
//                if (param.length() > 0) {
//                    imageLoader.displayImage(url,feedHolder.imageViewCoverImage ,options ,animateFirstListener);
//                }
                if (!TextUtils.isEmpty(mList.get(position).getCover())) {
                    Picasso.with(mContext).load(mList.get(position).getCover())
                            .placeholder(R.drawable.home_bg)
                            .into(feedHolder.imageViewCoverImage);
                }

                if (mList.get(position).getStatus().equals("online")) {
                    feedHolder.textViewStateText.setText("直播");
                    feedHolder.textViewStateText.setTextColor(mContext.getResources().getColor(R.color.black));
                    feedHolder.textViewLiveViewer.setText("" + mList.get(position).getUsers_count() + "人在看");
                    feedHolder.textViewStateText.setBackgroundResource(R.drawable.bg_rounded_zhibo_state_bg);
                } else {
                    feedHolder.textViewStateText.setText("回放");
                    feedHolder.textViewStateText.setTextColor(mContext.getResources().getColor(R.color.white));
                    feedHolder.textViewLiveViewer.setText("" + mList.get(position).getUsers_count() + "人看过");
                    feedHolder.textViewStateText.setBackgroundResource(R.drawable.bg_rounded_huifang_state_bg);
                }

                feedHolder.mCoverImgBorder.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mList.get(position).getStatus().equals("online")) {
                            if (mLiveAdapterCallback != null) {
                                Constants.setChooseRoomInfo(mList.get(position));
                                mLiveAdapterCallback.onItemClick(mList.get(position));
                            }
                        } else {
                            if (!TextUtils.isEmpty(mList.get(position).getTencentVideoUrl()) ||
                                    !TextUtils.isEmpty(mList.get(position).getTencent_file_id())) {
                                Intent tohistoryIntent = new Intent();
                                tohistoryIntent.setClass(mContext, PlayBackActivity.class);
                                tohistoryIntent.putExtra(PlayBackActivity.FLAG_FILE_ID, mList.get(position).getTencent_file_id());
                                tohistoryIntent.putExtra(PlayBackActivity.FLAG_ROOM_ID, String.valueOf(mList.get(position).getId()));
                                tohistoryIntent.putExtra(PlayBackActivity.FLAG_TENCENT_VIDEO_URL, mList.get(position).getTencentVideoUrl());
                                mContext.startActivity(tohistoryIntent);
                            } else {
                                Toast.makeText(mContext, "直播已结束", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }
                });

                break;
        }

    }


    @Override
    public int getItemViewType(int position) {
        if (mList == null || mList.size() == 0) {
            return TYPE_EMPTY;
        } else {
            return TYPE_FEED;
        }
    }

    @Override
    public int getItemCount() {
        if (mList == null || mList.size() == 0) {
            return 1;
        }
        return mList.size();
    }

    public class FeedHolder extends RecyclerView.ViewHolder {


        @InjectView(R.id.image_view_live_cover_image)
        ImageView imageViewCoverImage;
        @InjectView(R.id.image_btn_user_logo)
        RoundedImageView imageButtonUserLogo;
        @InjectView(R.id.text_view_user_name)
        TextView textViewUserName;
        @InjectView(R.id.text_view_live_title)
        TextView textViewLiveTitle;
        @InjectView(R.id.text_view_live_viewer)
        TextView textViewLiveViewer;
        @InjectView(R.id.text_view_live_praise)
        TextView textViewLivePraise;
        @InjectView(R.id.feed_share)
        ImageButton shareButton;
        @InjectView(R.id.content)
        TextView textViewContent;
        @InjectView(R.id.state_text)
        TextView textViewStateText;
        @InjectView(R.id.cover_image_border)
        FixedAspectRatioFrameLayout mCoverImgBorder;


        public FeedHolder(View view) {
            super(view);
            ButterKnife.inject(this, view);
        }
    }

    public class EmptyHolder extends RecyclerView.ViewHolder {

        @InjectView(R.id.info_text)
        TextView mInfoText;

        public EmptyHolder(View view) {
            super(view);
            ButterKnife.inject(this, view);
        }
    }

    private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }

    private LiveAdapterCallback mLiveAdapterCallback;

    public static interface LiveAdapterCallback {
        public void onItemClick(RoomBean liveVideoInfo);

        public void onShareBtnClick(RoomBean liveVideoInfo);
    }


}
